package pers.fjl.test.controller.admapi;

import pers.fjl.common.constant.MessageConstant;
import pers.fjl.common.entity.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import pers.fjl.common.po.Role;
import pers.fjl.test.annotation.IpRequired;
import pers.fjl.test.annotation.LoginRequired;
import pers.fjl.test.service.UserItemService;
import pers.fjl.test.utils.JWTUtils;
import pers.fjl.common.po.User;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@CrossOrigin
@RestController
@Slf4j
@Api(value = "信息管理模块", description = "管理用户信息验证")
@RequestMapping("/admapi")
public class IndexAdminController {
    @Resource
    private UserItemService userItemService;

    @PostMapping("/login")
    @IpRequired
    public Result login(@RequestBody User user, HttpServletRequest request) {
        log.info("用户名:[{}]", user.getUsername());
        log.info("密码:[{}]", user.getPassword());
        try {
            //认证成功，生成jwt令牌
            user.setLastIp((String) request.getAttribute("host"));
            System.out.println("indexAdminController:" + (String) request.getAttribute("host"));
            User userDB = userItemService.login(user);
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(userDB.getId()));
            payload.put("lastIp", userDB.getLastIp());
            payload.put("username", userDB.getUsername());
            String token = JWTUtils.getToken(payload);

            return new Result(true, "token生成成功", token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.ERROR, "token生成失败,请检查你的账号与密码是否匹配");
    }
}
